package util;

import java.io.IOException;
import java.net.SocketException;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;

public class ftpUtils {

	private FTPClient ftpClient = null;
	
	private String serverIP;
	private int serverPort;
	private String userName;
	private String userPassword;
	private String encoding;
	private boolean paveMode;
	private int fileType;
	
	public void setProperties(String serverIP,  int serverPort, String userName, 
			String userPassword, String encoding, boolean paveMode, String fileType) {
		this.serverIP = serverIP;
		this.serverPort = serverPort; 
		this.userName = userName; 
		this.userPassword = userPassword;
		this.paveMode = paveMode;
		this.encoding = encoding;
		this.fileType = 2;
		
		if(fileType.equalsIgnoreCase("ascii")) {
			this.fileType = 0;
		} else if(fileType.equalsIgnoreCase("else ")) {
			this.fileType = 1;
		} else if(fileType.equalsIgnoreCase("binary")) {
			this.fileType = 2;
		}
		
		ftpClient = new FTPClient();
	}
	
	private int ftpConnet() {
		int nRet = 0;
		
		ftpClient = new FTPClient();
		
		if(this.paveMode) {
			ftpClient.enterLocalPassiveMode();
		} else {
			ftpClient.enterLocalActiveMode();
		}
		ftpClient.setControlEncoding(encoding);
		try {
			ftpClient.connect(serverIP, serverPort);
			
		} catch (SocketException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} 
		
		if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
			try {
				ftpClient.logout();
				ftpClient.disconnect();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
		return nRet;
	}
	
	private int ftpDisconnect() {
		int nRet = 0;
		
		try {
			if(!ftpClient.logout()) {
				return -1;
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				ftpClient.disconnect();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return nRet;
	}
	private int changeDirectory() {
		int nRet = 0;
		
		
		
		return nRet;
	}
	
	public int downLoadFile(String remoteFile, String localFile) {
		int nRet = 0;
		nRet = ftpConnet();
		changeDirectory();
		
		ftpDisconnect();
		return nRet;
	}
	
	
}
